package main;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.Enumeration;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import domain.dao.ActionsDao;

public class ServerMain {

  public static void main(String[] args) {
    
    ServerConfig serverConfig = new ServerConfig();
    
    ServerScripts.InitiateRCF();
    
    ActionsDao actionsDao = new ActionsDao();
    actionsDao.prepareActions();
    
    IoAcceptor acceptor = new NioSocketAcceptor();
    
//    acceptor.getFilterChain().addLast("logger", new LoggingFilter());
    acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
    
    acceptor.setHandler(new ServerConnectionHandler());
    
    acceptor.getSessionConfig().setReadBufferSize(2048);
    acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);

    try {
      InetAddress address = InetAddress.getLocalHost();
      System.out.println("IP ==== " + address.getHostAddress());
      acceptor.bind(new InetSocketAddress(address, serverConfig.getPort()));
    } catch (UnknownHostException e1) {
      System.out.println("Unknown host ip");
    } catch (IOException e) {
      System.out.println("Port is in use");
    }
    
  }
}
